import React from "react";
import { Submit as FormilySubmit } from "../../packages/formily-antd-v5/src";
import {
  createBehavior,
  createResource,
  GlobalRegistry,
} from "../../packages/designable-core/src";
import { DnFC } from "../../packages/designable-react/src";
import { observer } from "../../packages/formily-reactive-react/src";
import { createVoidFieldSchema } from "../Field";
import { AllSchemas } from "../../schemas";
import { AllLocales } from "../../locales";

// Create a wrapper that observes language changes and provides default text
const SubmitWrapper: DnFC<React.ComponentProps<typeof FormilySubmit>> = observer((props) => {
  const getLocalizedDefaultText = () => {
    const lang = GlobalRegistry.getDesignerLanguage();
    const locales = AllLocales.Submit;
    
    // Get buttonText from locale files, fall back to title if not available
    if (locales[lang]) {
      return locales[lang].buttonText || locales[lang].title;
    }
    
    // Fallback to Chinese if language not found
    return locales["zh-CN"]?.buttonText || locales["zh-CN"]?.title || "提交";
  };

  // If children is not provided, use localized default text
  const children = props.children || getLocalizedDefaultText();
  
  return <FormilySubmit {...props} children={children} />;
});

export const Submit: DnFC<React.ComponentProps<typeof FormilySubmit>> = SubmitWrapper;

Submit.Behavior = createBehavior({
  name: "Submit",
  extends: ["Field"],
  selector: (node) => node.props["x-component"] === "Submit",
  designerProps: {
    propsSchema: createVoidFieldSchema(AllSchemas.Submit),
  },
  designerLocales: AllLocales.Submit,
});

Submit.Resource = createResource("Displays", {
  icon: "ButtonSource",
  elements: [
    {
      componentName: "Field",
      props: {
        type: "void",
        title: "Submit",
        "x-component": "Submit",
        "x-component-props": {
          type: "primary",
          htmlType: "submit",
          // Don't set children here - let the wrapper component handle it dynamically
        },
      },
    },
  ],
});
